package com.example.testmap.demos.web.serivce.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.example.testmap.demos.web.mapper.StudentMapper;
import com.example.testmap.demos.web.pojo.UserInfo;
import com.example.testmap.demos.web.serivce.PrintExcelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class PrintExcelServiceImpl implements PrintExcelService {

    @Autowired
    StudentMapper studentMapper;

    @Override
    /**
     * 打印Excel
     */
    public void print() {
        List<UserInfo> users = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            UserInfo user = UserInfo.builder()
                    .userId(i)
                    .userName("admin" + i)
                    .gender(i % 2 == 0 ? "男" : "女")
                    .salary(i * 1000.00)
                    .hireDate(new Date())
                    .build();
            users.add(user);
        }

       /* File file = new File("D:\\study\\excel\\user1.xlsx");
        try {
            file.createNewFile();
        } catch (IOException e) {

            throw new CustomException("文件生成错误");
        }*/
        Set<String> excludeField = new HashSet<>();
        excludeField.add("hireDate");
        excludeField.add("salary");

        String filename = "D:\\excelTest\\test.xlsx";

        // 向Excel中写入数据 也可以通过 head(Class<?>) 指定数据模板
        EasyExcel.write(filename, UserInfo.class)
                .sheet("用户信息")
                //.excludeColumnFiledNames(excludeField)
                .doWrite(users);
    }

    /**
     * 将Excel中的数据写到数据库中
     */
    @Override
    public void readMysql(UserInfo userInfo) {
        String filename = "D:\\excelTest\\test.xlsx";

        try {
            EasyExcel.read(filename, UserInfo.class, new AnalysisEventListener<UserInfo>() {
                @Override
                public void invoke(UserInfo user, AnalysisContext analysisContext) {
                    System.out.println("解析数据为"+user);

                    System.out.println("保存成功");
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {

                }
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }





}
